import { SVG } from '@svgdotjs/svg.js'

export default {
  data() {
    return {
      drawer: ''
    }
  },
  methods: {
    // 初始化画板
    initDraw() {
      if (!this.drawer) {
        this.drawer = SVG().addTo('#line-area').size('100%', '100%')
      }
      this.drawer.clear()
      const parent = this.$store.state.mind.rootCard
      this.handleCreate(parent)
    },
    // 根节点单独处理
    handleCreate(target) {
      this.$nextTick(() => {
        const { offsetTop, offsetLeft, offsetWidth, offsetHeight } = document.querySelector(`#${target.id}`)
        this.dp(target, [offsetLeft + offsetWidth, offsetTop + offsetHeight / 2])
      })
    },
    // 递归子节点绘制线条
    dp(parent, p_right) {
      const arr = this.$store.state.mind.nodeCards.filter((v) => v.parent[v.parent.length - 1] === parent.id)
      if (arr?.length) {
        arr.forEach((child) => {
          const { position } = child
          if (position === 'left') {
            const { offsetTop, offsetLeft, offsetWidth, offsetHeight } = document.querySelector(`#${child.id}`)
            this.dp(child, [offsetLeft - 44, offsetTop + offsetHeight / 2])
            this.drawLine(p_right, [offsetLeft + offsetWidth, offsetTop + offsetHeight / 2], child)
          } else {
            const { offsetTop, offsetLeft, offsetWidth, offsetHeight } = document.querySelector(`#${child.id}`)
            this.dp(child, [offsetLeft + offsetWidth, offsetTop + offsetHeight / 2])
            this.drawLine(p_right, [offsetLeft, offsetTop + offsetHeight / 2], child)
          }
        })
      }
    },
    // 画线
    drawLine(start, end, target) {
      // 如果已经存在先删除,否则会越画越多
      // SVG(`#svg-${target.id}`)?.remove()
      // 二级节点的需要添加展开收起图标的宽度
      const offset = target.parent.length === 1 ? 0 : 22
      this.drawer
        .path(this.cubicBezierPath(start[0] + offset, start[1], end[0], end[1]))
        // .line(start[0] + offset, start[1], end[0], end[1])
        .id(`svg-${target.id}`)
        .fill('none')
        .stroke({ color: target.active ? '#24A8FF' : '#e5e5e5', width: 2 })
    },
    cubicBezierPath(x1, y1, x2, y2) {
      // return 'M' + x1 + ' ' + y1 + ' C ' + (x1 + (x2 - x1) * 2 / 3) + ' ' + y1 + ', ' + x1 + ' ' + y2 + ', ' + x2 + ' ' + y2
      let cx1 = x1 + (x2 - x1) / 2
      let cy1 = y1
      let cx2 = cx1
      let cy2 = y2
      return [
        ['M', x1, y1],
        ['C', cx1, cy1, cx2, cy2, x2, y2]
      ]
    }
  }
}
